package com.example.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.common.to.es.SkuEsModel;
import com.example.common.utils.R;
import com.example.gulimall.search.config.GuliESConfig;
import com.example.gulimall.search.constant.EsConstant;
import com.example.gulimall.search.feign.ProductFeignService;
import com.example.gulimall.search.service.SearchService;
import com.example.gulimall.search.vo.AttrRespVo;
import com.example.gulimall.search.vo.SearchParam;
import com.example.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

@Slf4j
@Service("searchService")
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ProductFeignService productFeignService;
    @Override
    public SearchResult getSearchResult(SearchParam param){
        //构造搜索条件
        SearchRequest searchRequest=buildSearchRequest(param);
        SearchResult result=null;
        try {
            //ES搜索所需的结果
            SearchResponse response = client.search(searchRequest, GuliESConfig.COMMON_OPTIONS);
            //构造得到的结果
            result=buildSearchResult(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 利用输入的参数构造搜索的条件
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //拼接查询条件keyword
        if(StringUtils.isNotEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //拼接分类id
        if(param.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //拼接品牌id
        if(param.getBrandId()!=null&&param.getBrandId().size()!=0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        //拼接库存是否为空
        if(param.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }
        //拼接价格范围
        //1_500
        if(StringUtils.isNotEmpty(param.getSkuPrice())){
            String[] s = param.getSkuPrice().split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if(s.length==2){
                if(s[0]!=null&&s[0].length()!=0)
                    rangeQuery.gte(Integer.parseInt(s[0]));
                rangeQuery.lte(Integer.parseInt(s[1]));
            }else{
                if(param.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(Integer.parseInt(s[0]));
                }else{
                    rangeQuery.gte(Integer.parseInt(s[0]));
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        //拼接attr属性，是nested的属性
        //attrs=1_5寸:8寸&2_16G:8G
        if(param.getAttrs()!=null&&param.getAttrs().size()>0){
            param.getAttrs().forEach(attr->{
                BoolQueryBuilder nestedBoolBuilder = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                nestedBoolBuilder.must(QueryBuilders.termQuery("attrs.attrId",Long.parseLong(s[0])));
                String[] attrValue = s[1].split(":");
                nestedBoolBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValue));
                NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("attrs",nestedBoolBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            });
        }
        builder.query(boolQueryBuilder);
        //拼接排序数据 SaleCount_desc
        if(StringUtils.isNotEmpty(param.getSort())){
            String sort = param.getSort();
            String[] s = sort.split("_");
            builder.sort(s[0],s[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC);
        }
        //设置分页数据
        builder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGE_SIZE);
        builder.size(EsConstant.PRODUCT_PAGE_SIZE);
        //4. 高亮highlight
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }
        //分类聚合
        TermsAggregationBuilder catalogAgg=new TermsAggregationBuilder("catalogAgg");
        catalogAgg.field("catalogId").size(50);
        catalogAgg.subAggregation(new TermsAggregationBuilder("catalogNameAgg")
                .field("catalogName").size(1));
        builder.aggregation(catalogAgg);
        //品牌聚合
        TermsAggregationBuilder brandAgg = new TermsAggregationBuilder("brandAgg").field("brandId").size(20);
        brandAgg.subAggregation(new TermsAggregationBuilder("brandNameAgg").field("brandName").size(1));
        brandAgg.subAggregation(new TermsAggregationBuilder("brandImageAgg").field("brandImg").size(1));
        builder.aggregation(brandAgg);
        //attr聚合
        NestedAggregationBuilder nestedAggregationBuilder = new NestedAggregationBuilder("attrs", "attrs");
        TermsAggregationBuilder attrIdAgg = new TermsAggregationBuilder("attrIdAgg").field("attrs.attrId").size(20);
        attrIdAgg.subAggregation(new TermsAggregationBuilder("attrNameAgg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(new TermsAggregationBuilder("attrValueAgg").field("attrs.attrValue").size(50));
        nestedAggregationBuilder.subAggregation(attrIdAgg);
        builder.aggregation(nestedAggregationBuilder);
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},builder);
    }

    /**
     * 利用ES搜索后的结果封装结果数据
     * @param response
     * @param param
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        //封装商品信息
        SearchHits hits = response.getHits();
        if (hits.getHits() != null && hits.getHits().length != 0) {
            List<SkuEsModel> skuEsModelList = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highLight = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(highLight);
                }
                skuEsModelList.add(skuEsModel);
            }
            result.setProduct(skuEsModelList);
        }
        //2.分装分页信息
        //2.1当前页码
        result.setPageNum(param.getPageNum());
        //2.2总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //2.3总页码
        int totalPage = ((int) total + EsConstant.PRODUCT_PAGE_SIZE - 1) / EsConstant.PRODUCT_PAGE_SIZE;
        result.setTotalPages(totalPage);
        System.out.println(totalPage);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //3.查询结果涉及到的品牌
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        ParsedLongTerms brandAgg = aggregations.get("brandAgg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            //3.1得到品牌ID
            long brandId = bucket.getKeyAsNumber().longValue();
            Aggregations subAggs = bucket.getAggregations();
            //3.2得到品牌图片
            Terms brandImageAgg = subAggs.get("brandImageAgg");
            String brandImg = brandImageAgg.getBuckets().get(0).getKeyAsString();
            //3.3得到品牌名字
            Terms brandNameAgg = subAggs.get("brandNameAgg");
            String brandName = brandImageAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo(brandId, brandName, brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //查询所有分类
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = aggregations.get("catalogAgg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            long catalogId = bucket.getKeyAsNumber().longValue();
            Aggregations subAggs = bucket.getAggregations();
            ParsedStringTerms catalogNameAgg = subAggs.get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo(catalogId, catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //查询涉及到的所有属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrs = aggregations.get("attrs");
        ParsedLongTerms attrIdAgg = attrs.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            long attrId = bucket.getKeyAsNumber().longValue();
            Aggregations subAggs = bucket.getAggregations();
            ParsedStringTerms attrNameAgg = subAggs.get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attrValueAgg = subAggs.get("attrValueAgg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                String attrValue = attrValueAggBucket.getKeyAsString();
                attrValues.add(attrValue);
            }
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo(attrId, attrName, attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        List<String> attrList = param.getAttrs();
        if (attrList != null && attrList.size() > 0) {
            List<SearchResult.NavVo> collect = attrList.stream().map(attr -> {
                String[] s = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                navVo.setNavValue(s[1]);
                try {
                    R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                    if ((int) r.get("code") == 0) {
                        AttrRespVo attrRespVo = JSON.parseObject(JSON.toJSONString(r.get("attr")), new TypeReference<AttrRespVo>() {
                        });
                        navVo.setNavName(attrRespVo.getAttrName());
                    }
                } catch (NumberFormatException e) {
                    log.error("远程调用出错", e);
                }
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+", "%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + (replace.isEmpty() ? "" : "?" + replace));

                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }
        return result;
    }
}
